package reqx

import (
	"encoding/json"
	"fmt"

	"github.com/go-resty/resty/v2"
)

type restyClient struct {
	c *resty.Client
}

func NewRestyClient() RequestClient {
	return &restyClient{c: resty.New()}
}

func (rc *restyClient) Get(v interface{}, url string, params RequestOptions, headers RequestOptions) error {
	req := rc.c.R()

	if len(params) > 0 {
		req.SetQueryParams(params)
	}

	if len(headers) > 0 {
		req.SetHeaders(headers)
	}

	req.SetResult(v)
	req.ForceContentType("application/json")
	resp, err := req.Get(url)
	if err != nil {
		return err
	}
	if resp.StatusCode() != 200 {
		return fmt.Errorf("request.get other error: %s", resp.Body())
	}
	return nil
}

func (rc *restyClient) Post(v interface{}, url string, body interface{}, headers RequestOptions) error {
	req := rc.c.R()

	req.SetBody(body)

	req.SetHeader("Content-Type", "application/json")
	if len(headers) > 0 {
		req.SetHeaders(headers)
	}

	req.SetResult(v)

	resp, err := req.Post(url)
	if err != nil {
		return err
	}
	if resp.StatusCode() != 200 {
		return fmt.Errorf("request.post other error: %s", resp.Body())
	}
	return nil
}

func (rc *restyClient) PostForm(v interface{}, url string, body, headers RequestOptions) error {
	req := rc.c.R()

	req.SetFormData(body)

	if len(headers) > 0 {
		req.SetHeaders(headers)
	}

	resp, err := req.Post(url)
	if err != nil {
		return err
	}
	if resp.StatusCode() != 200 {
		return fmt.Errorf("request.post other error: %s", resp.Body())
	}

	ret := resp.String()
	err = json.Unmarshal([]byte(ret), &v)
	if err != nil {
		return fmt.Errorf("invalid response type")
	}

	return nil
}
